import { useStyle } from './Style';

export type ItemBase<T = unknown> = {
  title: string;
  key: string;
  group?: string;
} & T;

export type ItemGroup<T = unknown> = Pick<ItemBase, 'key' | 'title'> & { children: ItemBase<T>[] };

export interface LeftGroupMenuPorps<T = unknown> {
  items?: (ItemBase<T> | ItemGroup<T>)[];
  onChange?(value: ItemBase<T>): void;
  value?: string;
}

function isGroup(item: ItemBase | ItemGroup): item is ItemGroup {
  if ('children' in item) {
    if (item.children.length) {
      return true;
    }
  }
  return false;
}

function LeftGroupMenu<T = unknown>({ items = [], onChange, value }: LeftGroupMenuPorps<T>) {
  const cssStyle = useStyle();

  const _onChange = function (item: ItemBase<T>) {
    if (value !== item.key) {
      onChange?.(item);
    }
  };

  return (
    <ul className={cssStyle.styles.container}>
      {items?.map((mybeGroup) => {
        let children: ItemGroup<T>['children'] | undefined;
        if (isGroup(mybeGroup)) {
          children = mybeGroup.children;
        }
        const isTypeGroup = Boolean(children?.length);
        return (
          <li key={mybeGroup.key}>
            <div
              className={cssStyle.cx([
                isTypeGroup ? 'group_title' : 'item_title',
                'group-menu_title',
                { active: mybeGroup.key === value },
              ])}
              onClick={(e) => {
                e.stopPropagation();
                e.preventDefault();
                if (!isGroup(mybeGroup)) {
                  _onChange(mybeGroup);
                }
              }}
            >
              {mybeGroup.title}
            </div>
            {children ? (
              <ul>
                {children.map((item) => {
                  return (
                    <li key={item.key}>
                      <div
                        className={cssStyle.cx([
                          'group-menu_title item_title',
                          {
                            active: item.key === value,
                          },
                        ])}
                        onClick={(e) => {
                          e.stopPropagation();
                          e.preventDefault();
                          _onChange(item);
                        }}
                      >
                        {item.title}
                      </div>
                    </li>
                  );
                })}
              </ul>
            ) : null}
          </li>
        );
      })}
    </ul>
  );
}

export { LeftGroupMenu };
